package com.tiger.utils;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;

public class Json {
	private static JsonObjectMapper mapper = new JsonObjectMapper();
	static {
		mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

	public static <T> T fromJson(String json, Class<T> cls) {
		return mapper.convertValue(toJsonNode(json), cls);
	}

	public static <T> T fromJson(String json, TypeReference<T> type) {
		return mapper.convertValue(toJsonNode(json), type);
	}
	
	public static <T> T fromJson(JsonNode json, Class<T> cls) {
		return mapper.convertValue(json, cls);
	}
	
	public static <T> T fromJson(JsonNode json, TypeReference<T> type) {
		return mapper.convertValue(json, type);
	}

	public static JsonNode toJsonNode(String content) {
		try {
			return mapper.readTree(content);
		} catch (IOException e) {
		}
		return null;
	}
	
	public static String toJson(Object obj){
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	} 
}
